<?php

namespace App\Http\Controllers\Admin;

use App\Exceptions\ApiException;
use App\Http\Controllers\Controller;
use App\Models\Admin;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;

class LoginController extends Controller
{

    public function login(Request $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');
        $remember = $request->input('remember'); // 是否记住登录

        $admin = Admin::where('username', $username)->first();
        if (!$admin) return $this->failed('用户不存在');

        // 是否是自动登录
        if ($remember) {
            Auth::login($admin);
            $token = $admin->createToken('admin')->plainTextToken;
            return $this->successful('自动登录成功', compact('token', 'admin'));
        }

        $request->validate([
            'username' => ['required', 'exists:admins,username'],
            'password' => ['required']
        ]);
        if (!Hash::check($password, $admin->password)) {
            return $this->fail(199, '密码错误');
        }
        Auth::login($admin);
        $token = $admin->createToken('admin')->plainTextToken;

        return $this->successful(compact('token', 'admin'));
    }

    public function show()
    {
        if (auth()->check()) {
            return $this->successful(auth()->user());
        }
        return response()->json(['message' => 'Unauthorized'], 401);
    }

    public function update(Request $request)
    {
        $nickname = $request->nickname;
        $password = $request->password;

        $admin = Admin::find(auth()->id());
        if ($admin) {
            $password && $admin->password = Hash::make($password);
            $admin->nickname = $nickname;
            $admin->save();
            return $this->successful('修改成功', $admin->refresh());
        }
        return $this->failed('修改失败');
    }

    public function logout()
    {
        $id = auth()->id();
        Auth::logout();
        return $this->successful('退出成功', $id);
    }
}
